var fs = require('fs')

var express = require('express')

var Student = require('./student')
const { log } = require('console')

var router = express.Router()

router.get('/', function (req, res) {

    // fs.readFile('db.json', function (err, data) {
    //     if (err) {
    //         return res.send('文件读取失败：', err)
    //     }

    //     var students = JSON.parse(data.toString()).students
    //     res.render('index.html', {
    //         fruits: [
    //             '苹果',
    //             '香蕉',
    //             '梨子',
    //             '橘子'
    //         ],
    //         students: students
    //     })
    // })

    Student.find(function(err, students){
        if(err){
            return res.status(500).send('Server error')
        }
        res.render('index.html',{
            fruits: [
                '苹果',
                '香蕉',
                '梨子',
                '橘子'
            ],
            students: students
        })
    })


})

router.get('/students/new', function (req, res) {
    res.render('new.html')
})

router.post('/students/new', function (req, res) {
    var student = req.body
    Student.save(student,function(err){
        if(err){
            return res.status(500).send('Server error')
        }
        res.redirect('/')
    })
})

router.get('/students/edit', function (req, res) {
    Student.findById(parseInt(req.query.id), function(err, student) {
        if (err) {
            return res.status(500).send('Server error')
        }
        res.render('edit.html',{
            student: student
        })
    })
})

router.post('/students/edit', function (req, res) {
    var student = req.body
    Student.update(student,function(err){
        if(err){
            return res.status(500).send('Server error')
        }
        res.redirect('/')
    })
})

router.get('/students/delete', function (req, res) {
    var id = req.query.id
    Student.delete(id, function (err, data) {
        if (err) {
            return res.status(500).send('Server error')
        }
        res.redirect('/')
    })
})

module.exports = router